import { getCampusSelector } from '@/api/campus/campus'
import Divider from '@/components/Generator/index/RightComponents/Divider'
import request from '@/utils/request'
export default {
  components: { Divider },
  props: [],
  data() {
    /**
     * 校验上传的督导检查表是否已选择
     * @param {Object} rule 规则对象
     * @param {Array} value 当前字段值
     * @param {Function} callback 校验回调
     */
    const validateReviewDoc = (rule, value, callback) => {
      if (value === '' || value.length < 1) {
        callback(new Error('请上传校区运营规范检查表'))
      } else {
        callback()
      }
    }
    /**
     * 校验改进方案是否已上传
     * @param {Object} rule 规则对象
     * @param {Array} value 当前字段值
     * @param {Function} callback 校验回调
     */
    const validateImprove = (rule, value, callback) => {
      if (value === '' || value.length < 1) {
        callback(new Error('请上传与校区达成一致的具体改进方案'))
      } else {
        callback()
      }
    }
    /**
     * 校验提交前承诺声明是否已勾选
     * @param {Object} rule 规则对象
     * @param {Boolean} value 当前字段值
     * @param {Function} callback 校验回调
     */
    const validateConfirmDeclaration = (rule, value, callback) => {
      if (value === true) {
        callback()
      } else {
        callback(new Error('请勾选承诺声明后再提交'))
      }
    }

    return {
      loading: false,
      setting: {},
      eventType: '',
      dataForm: {
        id: '',
        brand: undefined,
        campusId: undefined,
        counselor: undefined,
        startDate: undefined,
        endDate: undefined,
        type: undefined,
        noonNum: 0,
        nightNum: 0,
        allNum: 0,
        otherNum: '',
        degree: 0,
        total: 0,
        priceDoc: [], // 校区价格表
        reviewDoc: [],
        improve: [],
        // 提交前承诺声明（必须勾选）
        commitment: true,
        // checklist: [],
        place: [],
        flow: [],
        classes: [],
        sparkle: '',
        deficiency: '',
        regularity: [],
        team: [],
        profit: [],
        score: 0,
        pickerDate: [],
        openDate: ''
      },
      regularity1: 0,
      regularity2: 0,
      regularity3: 0,
      team1: 0,
      team2: 0,
      team3: 0,
      profit1: 0,
      profit2: 0,
      profit3: 0,
      rules: {
        brand: [
          {
            required: true,
            message: '请选择校区品牌',
            trigger: 'change'
          }
        ],
        campusId: [
          {
            required: true,
            message: '请选择辅导校区',
            trigger: 'change'
          }
        ],
        counselor: [
          {
            required: true,
            message: '请输入督导师',
            trigger: 'change'
          }
        ],
        pickerDate: [
          {
            required: true,
            message: '请选择督导时间',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择辅导类型',
            trigger: 'change'
          }
        ],
        sparkle: [
          {
            required: true,
            message: '请输入校区亮点',
            trigger: 'blur'
          }
        ],
        deficiency: [
          {
            required: true,
            message: '请输入校区不足',
            trigger: 'blur'
          }
        ],
        reviewDoc: [{ required: true, validator: validateReviewDoc, trigger: 'change' }],
        improve: [{ required: true, validator: validateImprove, trigger: 'change' }],
        // 承诺声明必须勾选
        commitment: [{ required: true, validator: validateConfirmDeclaration, trigger: 'change' }]
      },
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      brandOptions: [],
      campusOptions: [],
      campusLoading: false,
      typeOptions: [
        {
          name: '教务辅导',
          value: '1'
        },
        {
          name: '日常督导',
          value: '2'
        }
      ]
    }
  },
  computed: {},
  watch: {
    'dataForm.brand': {
      async handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          try {
            this.campusLoading = true
            await getCampusSelector({
              brand: this.dataForm.brand,
              fields: 'id,fullName,openDate,degreeCount,bedCount'
            }).then(res => {
              this.campusOptions = Array.isArray(res.data) ? res.data : []
            })
          } catch (err) {
            console.error('加载校区下拉选项失败:', err)
            this.$message.error('校区选项加载失败')
            this.campusOptions = []
          } finally {
            this.campusLoading = false
          }
        }
      }
    },
    'dataForm.campusId': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          if (!this.dataForm.id) {
            let item = this.campusOptions.filter(item => item.id == this.dataForm.campusId)
            item ? (this.dataForm.openDate = item[0].openDate) : ''
            item ? (this.dataForm.degree = item[0].degreeCount) : ''
            item ? (this.dataForm.bed = item[0].bedCount) : ''
          }
        }
      }
    }
  },
  created() {},
  mounted() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    deleteSparkleItem(key, index) {
      this.dataForm[key].splice(index, 1)
    },
    addSparkleItem(key) {
      this.dataForm[key].push({})
    },
    goBack() {
      this.$emit('refresh')
    },
    init(data) {
      this.setting = data
      this.dataForm.id = data.id || ''
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (this.dataForm.id) {
          request({
            url: '/api/campus/academic/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataForm = Object.assign(this.dataForm, res.data)
            // if (!this.dataForm.summarize) this.dataForm.summarize = [];
            if (!this.dataForm.improve) this.dataForm.improve = []
            if (!this.dataForm.reviewDoc) this.dataForm.reviewDoc = []

            // if (!this.dataForm.checklist) this.dataForm.checklist = [];
            // if (!this.dataForm.sparkle) this.dataForm.sparkle = [];
            // if (!this.dataForm.lack) this.dataForm.lack = [];
            if (this.dataForm.regularity) {
              this.regularity1 = this.dataForm.regularity[0]
              this.regularity2 = this.dataForm.regularity[1]
              this.regularity3 = this.dataForm.regularity[2]
            }
            if (this.dataForm.team) {
              this.team1 = this.dataForm.team[0]
              this.team2 = this.dataForm.team[1]
              this.team3 = this.dataForm.team[2]
            }
            if (this.dataForm.profit) {
              this.profit1 = this.dataForm.profit[0]
              this.profit2 = this.dataForm.profit[1]
              this.profit3 = this.dataForm.profit[2]
            }
            if (this.dataForm.startDate && this.dataForm.endDate) {
              this.dataForm.pickerDate = [this.dataForm.startDate, this.dataForm.endDate]
            }
            /*if (this.dataForm.sparkle) {
              this.dataForm.sparkle = JSON.parse(this.dataForm.sparkle)
            }
            if (this.dataForm.lack) {
              this.dataForm.lack = JSON.parse(this.dataForm.lack)
            }*/
          })
        }
      })
    },

    handlePickerDateChange(time) {
      this.dataForm.startDate = time[0]
      this.dataForm.endDate = time[1]
    },
    setCurrentValue() {
      this.dataForm.score = (this.team1 + this.team2 + this.team3 + this.profit1 + this.profit1 + this.profit3 + this.regularity1 + this.regularity2 + this.regularity3) * 2 + 10
    },
    dataFormSubmit(eventType) {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          // 额外校验：提交前必须勾选承诺声明
          if (eventType === 'submit' && this.dataForm.commitment !== true) {
            this.$message.error('请勾选承诺声明后再提交')
            return
          }
          if (eventType === 'audit' || eventType === 'reject') {
            this.$emit('eventReciver', this.dataForm, eventType)
            return
          }
          this.dataForm.flowState = eventType === 'submit' ? 0 : 1
          this.eventType = eventType
          this.dataForm.regularity = [this.regularity1, this.regularity2, this.regularity3]
          this.dataForm.team = [this.team1, this.team2, this.team3]
          this.dataForm.profit = [this.profit1, this.profit2, this.profit3]

          if (this.eventType === 'submit') {
            this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
              type: 'warning'
            }).then(() => {
              this.request()
            })
          } else {
            this.request()
          }
        }
      })
    },
    request() {
      let data = { ...this.dataForm }
      /* if (data.sparkle && data.sparkle.length > 0) {
         data.sparkle = JSON.stringify(data.sparkle)
       }
       if (data.lack && data.lack.length > 0) {
         data.lack = JSON.stringify(data.lack)
       }*/
      this.dataForm.id
        ? request({
            url: `/api/campus/academic/${this.dataForm.id}`,
            method: 'put',
            data: data
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.$emit('close', true)
              }
            })
          })
        : request({
            url: `/api/campus/academic`,
            method: 'post',
            data: data
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.$emit('close', true)
              }
            })
          })
    },
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return true
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.read
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return !item.write
    }
  }
}
